{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Recommendations for user 0\n",
      "Item 2\n",
      "Item 3\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 生成示例数据\n",
    "user_items = np.array([\n",
    "    [4, 5, 0, 0, 1],\n",
    "    [5, 0, 3, 4, 0],\n",
    "    [0, 4, 0, 0, 2],\n",
    "    [1, 0, 4, 3, 0]\n",
    "])\n",
    "\n",
    "# 计算物品之间的相似度（余弦相似度）\n",
    "def item_similarity(user_items):\n",
    "    item_count = user_items.shape[1]\n",
    "    similarity_matrix = np.zeros((item_count, item_count))\n",
    "    for i in range(item_count):\n",
    "        for j in range(item_count):\n",
    "            if i == j:\n",
    "                continue\n",
    "            item_i = user_items[:, i]\n",
    "            item_j = user_items[:, j]\n",
    "            # 计算余弦相似度\n",
    "            similarity = np.dot(item_i, item_j) / (np.linalg.norm(item_i) * np.linalg.norm(item_j))\n",
    "            similarity_matrix[i, j] = similarity\n",
    "    return similarity_matrix\n",
    "\n",
    "# 基于相似度的物品选择\n",
    "def item_based_recommendation(user_items, similarity_matrix, user_id, top_n=3):\n",
    "    user_history = user_items[user_id]\n",
    "    candidate_items = np.argsort(-user_history)  # 按评分降序排序\n",
    "    recommendations = []\n",
    "    for item in candidate_items:\n",
    "        if user_history[item] == 0:\n",
    "            recommendations.append(item)\n",
    "        if len(recommendations) >= top_n:\n",
    "            break\n",
    "    return recommendations\n",
    "\n",
    "# 示例使用\n",
    "similarity_matrix = item_similarity(user_items)\n",
    "user_id = 0\n",
    "recommendations = item_based_recommendation(user_items, similarity_matrix, user_id)\n",
    "print(\"Recommendations for user\", user_id)\n",
    "for item in recommendations:\n",
    "    print(\"Item\", item)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
